#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""完整的启动和监控测试"""

import requests
import time
import subprocess
import os
import json

print("=== 完整测试流程 ===")

# 1. 清理旧进程
print("\n1. 清理旧进程...")
subprocess.run(["pkill", "-f", "python.*app.py"], capture_output=True)
time.sleep(2)

# 2. 启动服务
print("\n2. 启动API服务...")
app_process = subprocess.Popen(
    ["python3", "app.py"],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)

print("   等待服务启动...")
time.sleep(5)

# 3. 检查服务状态
print("\n3. 检查服务状态...")
try:
    response = requests.get("http://localhost:5000/health", timeout=5)
    print(f"   ✓ 健康检查: {response.status_code}")
    print(f"   响应: {response.text}")
except Exception as e:
    print(f"   ✗ 服务未响应: {e}")
    stdout, stderr = app_process.communicate(timeout=5)
    print("   标准输出:", stdout)
    print("   错误输出:", stderr)
    exit(1)

# 4. 获取当前状态
print("\n4. 获取监控状态...")
try:
    response = requests.get("http://localhost:5000/api/status", timeout=5)
    status = response.json()
    print(f"   监控状态: {status.get('monitoring_status', '未知')}")
    print(f"   房间URL: {status.get('room_url', '未设置')}")
    print(f"   是否正在监控: {status.get('is_monitoring', False)}")
except Exception as e:
    print(f"   ✗ 获取状态失败: {e}")

# 5. 启动监控
print("\n5. 启动监控...")
try:
    headers = {'Content-Type': 'application/json'}
    response = requests.post("http://localhost:5000/api/start", headers=headers, json={}, timeout=30)
    result = response.json()
    print(f"   响应: {result}")
    
    if result.get('success'):
        print("   ✓ 监控启动成功")
    else:
        print(f"   ✗ 监控启动失败: {result.get('message')}")
except Exception as e:
    print(f"   ✗ 启动监控失败: {e}")

# 6. 等待数据收集
print("\n6. 等待数据收集...")
for i in range(10):
    print(f"   等待中... {i+1}/10")
    time.sleep(3)
    
    # 检查问题列表
    try:
        response = requests.get("http://localhost:5000/api/questions", timeout=5)
        questions = response.json()
        if questions.get('questions'):
            print(f"\n   ✓ 收集到 {len(questions['questions'])} 个问题!")
            for q in questions['questions'][:5]:  # 显示前5个
                print(f"      - {q.get('user')}: {q.get('question')}")
            break
    except:
        pass

# 7. 检查最终状态
print("\n7. 最终检查...")
try:
    response = requests.get("http://localhost:5000/api/questions", timeout=5)
    questions = response.json()
    print(f"   问题总数: {len(questions.get('questions', []))}")
    
    response = requests.get("http://localhost:5000/api/status", timeout=5)
    status = response.json()
    print(f"   队列大小: {status.get('queue_size', 0)}")
except Exception as e:
    print(f"   ✗ 检查失败: {e}")

# 8. 检查日志
print("\n8. 检查日志...")
log_file = "live_monitor.log"
if os.path.exists(log_file):
    with open(log_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        print("   最后20行日志:")
        for line in lines[-20:]:
            line = line.strip()
            if "成功提取评论" in line or "问题已入队" in line or "发现" in line:
                print(f"     {line}")

# 9. 停止服务
print("\n9. 停止服务...")
try:
    requests.post("http://localhost:5000/api/stop", timeout=5)
    print("   ✓ 已发送停止请求")
except:
    pass

app_process.terminate()
print("\n=== 测试完成 ===")